package org.jwcloud.project.module.zx.info.service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.jwcloud.project.module.util.Constant;
import org.jwcloud.project.module.util.UUIDGenerator;
import org.jwcloud.project.module.zx.base.BaseServiceImpl;
import org.jwcloud.project.module.zx.dao.RtaCMsgUploadFileDAO;
import org.jwcloud.project.module.zx.dao.RtaItemInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaItemSzColDAO;
import org.jwcloud.project.module.zx.dao.RtaItemSzInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaItemUploadReplaceDAO;
import org.jwcloud.project.module.zx.dao.RtaProTaskInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaProjectInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaTaskInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaTaskItemRelDAO;
import org.jwcloud.project.module.zx.dao.RtaTaskSpLogDAO;
import org.jwcloud.project.module.zx.dao.RtaTaskSpPersonDAO;
import org.jwcloud.project.module.zx.dao.RtaTaskSzInfoDAO;
import org.jwcloud.project.module.zx.dao.RtaWorkInfoDAO;
import org.jwcloud.project.module.zx.db.domain.RtaCMsgUploadFile;
import org.jwcloud.project.module.zx.db.domain.RtaItemInfo;
import org.jwcloud.project.module.zx.db.domain.RtaItemSzCol;
import org.jwcloud.project.module.zx.db.domain.RtaItemSzInfo;
import org.jwcloud.project.module.zx.db.domain.RtaProTaskInfo;
import org.jwcloud.project.module.zx.db.domain.RtaProjectInfo;
import org.jwcloud.project.module.zx.db.domain.RtaTaskInfo;
import org.jwcloud.project.module.zx.db.domain.RtaTaskItemRel;
import org.jwcloud.project.module.zx.db.domain.RtaTaskSpLog;
import org.jwcloud.project.module.zx.db.domain.RtaTaskSpPerson;
import org.jwcloud.project.module.zx.db.domain.RtaTaskSzInfo;
import org.jwcloud.project.module.zx.db.domain.RtaWorkInfo;
import org.jwcloud.project.module.zx.mongo.MongoTemplateHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.SetOperators.SetIsSubset;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jw.mid.mm.comm.common.repository.CrudRepository;
import com.jw.mid.mm.comm.error.exception.BusiRuntimeException;

@Service

public class InfoServiceImpl extends BaseServiceImpl implements InfoService {
	@Autowired
	private RtaWorkInfoDAO rtaWorkInfoDAO;
	@Autowired
	private RtaProjectInfoDAO rtaProjectInfoDAO;
	// 任务配置表（任务ID唯一）
	@Autowired
	private RtaTaskInfoDAO rtaTaskInfoDAO;
	// 任务设置表
	@Autowired
	private RtaTaskSzInfoDAO rtaTaskSzInfoDAO;
	@Autowired
	private RtaTaskItemRelDAO rtaTaskItemRelDAO;
	@Autowired
	private RtaItemSzColDAO rtaItemSzColDAO;
	@Autowired
	private RtaItemSzInfoDAO rtaItemSzInfoDAO;
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private RtaProTaskInfoDAO rtaProTaskInfoDAO;
	@Autowired
	private RtaTaskSpLogDAO rtaTaskSpLogDAO;
	@Autowired
	private RtaTaskSpPersonDAO rtaTaskSpPersonDAO;
	@Autowired
	private RtaCMsgUploadFileDAO rtaCMsgUploadFileDAO;
	@Autowired
	private RtaItemUploadReplaceDAO rtaItemUploadReplaceDAO;
	@Autowired
	private MongoTemplateHelp mongoTemplateHelp;

	@Override
	public CrudRepository<Object, Long> getRepository() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TodoListTree todoList(Integer prjid, Map<String, Object> user) {
		String orgId = (String) user.get("ORG_ID");
		TodoListTree todoListTree = new TodoListTree();
		// 查询项目基本信息
		RtaProjectInfo rtaProjectInfo = rtaProjectInfoDAO.findById(prjid);
		if (rtaProjectInfo != null) {
			todoListTree.setId(rtaProjectInfo.getId().toString());
			todoListTree.setName(rtaProjectInfo.getProjectName());
			// 模板ID
			Integer tid = rtaProjectInfo.getRelTemplateId();

			// 查询阶段
			String appPhaseKey = Constant.APP_PHASE_KEY;

			String[] appPhaseKeys = appPhaseKey.split(",");
			List<TodoListTree> appPhaseList = new ArrayList<TodoListTree>();
			for (String keys : appPhaseKeys) {
				String[] key = keys.split(":");
				String appPhase = key[0];
				String name = key[1];
				TodoListTree appPhaseTree = new TodoListTree();
				appPhaseTree.setId(appPhase);
				appPhaseTree.setName(name);
				//
				// 查询模板对应的工作
				List<RtaWorkInfo> listRtaWorkInfo = rtaWorkInfoDAO.findByTemplateIdAppPhase(tid, appPhase);
				List<TodoListTree> workList = new ArrayList<TodoListTree>();
				for (RtaWorkInfo rtaWorkInfo : listRtaWorkInfo) {
					Integer workId = rtaWorkInfo.getId();
					String workName = rtaWorkInfo.getWorkName();
					TodoListTree mapRtaWorkInfo = new TodoListTree();
					mapRtaWorkInfo.setId(workId.toString());
					mapRtaWorkInfo.setName(workName);
					mapRtaWorkInfo.setAppPhase(rtaWorkInfo.getAppPhase());
					mapRtaWorkInfo.setIsWork("1");

					// 查询工作对应的任务
					List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(rtaWorkInfo.getId());
					List<TodoListTree> taskList = new ArrayList<TodoListTree>();
					for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {

						Integer taskSzId = rtaTaskInfo.getRelSz();
						RtaTaskSzInfo rtaTaskSzInfo = rtaTaskSzInfoDAO.findById(taskSzId);
						if (rtaTaskSzInfo != null) {
							// TODO
							RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjid, workId,
									rtaTaskInfo.getId());
							if (rtaProTaskInfo != null) {
								TodoListTree todoListTreeTask = new TodoListTree();

								// 任务配置id
								todoListTreeTask.setId(rtaTaskInfo.getId().toString());
								todoListTreeTask.setTaskPzId(rtaTaskInfo.getId());
								// 任务设置ID
								todoListTreeTask.setTaskSzId(rtaTaskSzInfo.getId());
								todoListTreeTask.setName(rtaTaskSzInfo.getTaskName());
								todoListTreeTask.setIsTask("1");
								// 是否有更新的后没有提交的要件 1 有更新 0 没有更新
								String haveNewItem = "0";
								// if (rtaProTaskInfo.getSpFlag()==null ||
								// Integer.valueOf(rtaProTaskInfo.getSpFlag()) <= 2) {

								// 判断要件中是否存在未提交的要件
								Query query = new Query();
								query.addCriteria(Criteria.where("prjId").is(prjid));

								query.addCriteria(Criteria.where("taskId").is(rtaTaskInfo.getId()));
								// query.addCriteria(Criteria.where("itemId").is(itemId));
								List<Map> list = mongoTemplate.find(query, Map.class, prjid.toString());
								for (Map map : list) {
									Map itemInfo = (Map) map.get("itemInfo");
									String flag = (String) itemInfo.get("spFlag");
//									if ("0".equals(flag)) {
//										haveNewItem = "1";
//									}

									if (flag == RtaProTaskInfo.SP_FLAG_INIT) {
										haveNewItem = "1";
									}

								}
								todoListTreeTask.setHaveNewItem(haveNewItem);
//									} else {
//										todoListTreeTask.setHaveNewItem(rtaProTaskInfo.getSpFlag());
//									}
								// 审批标志
								todoListTreeTask.setSpFlag(rtaProTaskInfo.getSpFlag());

								List<RtaTaskSpPerson> rtaTaskSpPersons = rtaTaskSpPersonDAO
										.searchByTaskId(rtaTaskInfo.getId());
								if (rtaTaskSpPersons != null && rtaTaskSpPersons.size() > 0) {
									todoListTreeTask.setNeedApproved("1");
								} else {
									todoListTreeTask.setNeedApproved("0");
								}
								//
								todoListTreeTask.setTaskStartDate(rtaProTaskInfo.getStartTime());

								Date theDoneDate = rtaProTaskInfo.getDoneTime();
								Date theStartTime = rtaProTaskInfo.getStartTime();
								Integer theDurTime = rtaProTaskInfo.getDurTime();
								if (theDoneDate == null && theDurTime != null && theStartTime != null) {
									Calendar calendar = new GregorianCalendar();
									calendar.setTime(theStartTime);
									calendar.add(calendar.DATE, theDurTime);
									theDoneDate = calendar.getTime();
								}
								// 设置任务状态
								if ("1".equalsIgnoreCase(rtaProTaskInfo.getIsDone())) {
									todoListTreeTask.setStatus("03");
								} else if (0 == rtaProTaskInfo.getIsCurrent()) {
									todoListTreeTask.setStatus("01");
								} else {
									todoListTreeTask.setStatus("02");
								}
								// TODO 判断责任部门
								String dutyDeptId = rtaTaskInfo.getDutyDept();
								if (orgId != null && dutyDeptId != null) {
									//
									Map<String, Object> myDept = baseDAO.searchDeptInfo(orgId);
									Map<String, Object> dept = baseDAO.searchDeptInfo(dutyDeptId);
									if (myDept != null && dept != null) {
										String myDeptPath = (String) myDept.get("path");
										String deptPath = (String) dept.get("path");
										if (orgId.equalsIgnoreCase(dutyDeptId)) {
											todoListTreeTask.setIsDutyDept("1");
										} else if (deptPath != null && myDeptPath != null
												&& myDeptPath.startsWith(deptPath)
												&& !myDeptPath.equalsIgnoreCase(deptPath)) {
											todoListTreeTask.setIsDutyDept("1");
										} else {
											todoListTreeTask.setIsDutyDept("0");
										}
									}
								} else {
									todoListTreeTask.setIsDutyDept("0");
								}

								List<RtaTaskItemRel> rtaTaskItemRels = rtaTaskItemRelDAO
										.findBytaskId(rtaTaskInfo.getRelSz());
								String uploadLimit = "01";
								for (RtaTaskItemRel rtaTaskItemRel : rtaTaskItemRels) {
									if ("02".equalsIgnoreCase(rtaTaskItemRel.getUploadType())) {
										uploadLimit = "02";
									}
								}
								todoListTreeTask.setUploadLimit(uploadLimit);

								todoListTreeTask.setTaskDoneDate(theDoneDate);
								// 配置表
								todoListTreeTask.setRtaProTaskInfo(rtaProTaskInfo);
								// 设置表
								todoListTreeTask.setRtaTaskSzInfo(rtaTaskSzInfo);
								//
								taskList.add(todoListTreeTask);
							}

						}
						// }
					}
					mapRtaWorkInfo.setSubList(taskList);
					if (mapRtaWorkInfo.getSubList() != null && mapRtaWorkInfo.getSubList().size() > 0) {
						workList.add(mapRtaWorkInfo);
					}
				}
				appPhaseTree.setSubList(workList);
				if (appPhaseTree.getSubList() != null && appPhaseTree.getSubList().size() > 0) {
					appPhaseList.add(appPhaseTree);
				}
			}
			todoListTree.setSubList(appPhaseList);
		}
		return todoListTree;
	}

	@Override
	public List<RtaItemSzCol> searchItemColList(Integer itemId) {

		List<RtaItemSzCol> rtaItemSzColList = rtaItemSzColDAO.findByItemid(itemId);

		// 附件数量
		RtaItemSzCol rtaItemInfo1 = new RtaItemSzCol();
		rtaItemInfo1.setColName("附件数量");
		rtaItemInfo1.setColType("1");
		rtaItemSzColList.add(rtaItemInfo1);
		// 完成人
		RtaItemSzCol rtaItemInfo2 = new RtaItemSzCol();
		rtaItemInfo2.setColName("完成人");
		rtaItemInfo2.setColType("1");
		rtaItemSzColList.add(rtaItemInfo2);
		// 完成部门
		RtaItemSzCol rtaItemInfo3 = new RtaItemSzCol();
		rtaItemInfo3.setColName("完成部门");
		rtaItemInfo3.setColType("1");
		rtaItemSzColList.add(rtaItemInfo3);
		// 完成时间
		RtaItemSzCol rtaItemInfo4 = new RtaItemSzCol();
		rtaItemInfo4.setColName("完成时间");
		rtaItemInfo4.setColType("1");
		rtaItemSzColList.add(rtaItemInfo4);

		// 是否替换
		RtaItemSzCol rtaItemInfo5 = new RtaItemSzCol();
		rtaItemInfo5.setColName("是否替换");
		rtaItemInfo5.setColType("否");
		rtaItemSzColList.add(rtaItemInfo5);

		// 替换说明
		RtaItemSzCol rtaItemInfo6 = new RtaItemSzCol();
		rtaItemInfo6.setColName("替换说明");
		rtaItemInfo6.setColType("1");
		rtaItemSzColList.add(rtaItemInfo6);
		return rtaItemSzColList;
	}

	@Override
	public void saveItemInfo(Integer prjId, Integer workId, Integer taskId, Integer itemId, Map<String, Object> infos,
			Map<String, Object> userInfo) {

		List<String> fileIdList = (List) infos.get("fileIdList");
		String infoId = UUIDGenerator.getUUID();
		infos.put("infoId", infoId);
		// 附件数量
		List<RtaCMsgUploadFile> newfileIdList = new ArrayList();
		if (fileIdList != null) {
			infos.put("附件数量", fileIdList.size());
			for (String fileId : fileIdList) {
				RtaCMsgUploadFile rtaCMsgUploadFile = (RtaCMsgUploadFile) rtaCMsgUploadFileDAO.findById(fileId);
				newfileIdList.add(rtaCMsgUploadFile);
			}
		} else {
			infos.put("附件数量", 0);
		}

		infos.put("fileIdList", newfileIdList);
		// 完成人
		infos.put("完成人编码", userInfo.get("USER_ID"));
		infos.put("完成人", getUserName((String) userInfo.get("USER_ID")));
		// 完成部门
		infos.put("完成部门编码", userInfo.get("ORG_ID"));
		infos.put("完成部门", getDeptName((String) userInfo.get("ORG_ID")));
		// 完成时间
		Timestamp d = new Timestamp(System.currentTimeMillis());
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date(d.getTime());
		infos.put("完成时间", format.format(date));
		infos.put("是否替换", "否");
		// 任务未提交
		infos.put("spFlag", RtaProTaskInfo.SP_FLAG_INIT);

		//
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("prjId", prjId);
		map.put("workId", workId);
		map.put("taskId", taskId);
		map.put("itemId", itemId);
		map.put("itemInfo", infos);
		mongoTemplate.save(map, prjId.toString());
		//
		Map<String, Object> parm = new HashMap<String, Object>();
		// rel_task_info varchar(300) COMMENT 'rta_task_info.id',
		RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjId, null, taskId);
		parm.put("rel_task_info", rtaProTaskInfo.getId());
		// rel_task_item_rel varchar(300) COMMENT 'rta_task_item_rel.id',
		parm.put("rel_task_item_rel", itemId);
		//
		parm.put("rel_item_info_id", infoId);
		// is_replace varchar(50) COMMENT '1是替换 0不是',
		parm.put("is_replace", "0");
		rtaItemUploadReplaceDAO.saveReplaceInfo(parm);

	}

	@Override
	public List searchItemInfo(Integer prjId, Integer workId, Integer taskId, Integer itemId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("prjId", prjId);
		map.put("workId", workId);
		map.put("taskId", taskId);
		Query query = new Query();
		query.addCriteria(Criteria.where("prjId").is(prjId));
		query.addCriteria(Criteria.where("workId").is(workId));
		query.addCriteria(Criteria.where("taskId").is(taskId));
		query.addCriteria(Criteria.where("itemId").is(itemId));
		List<Map> list = mongoTemplate.find(query, Map.class, prjId.toString());
		return list;
	}

	@Override
	public void updateItemInfo(Integer prjId, String infoId, Map<String, Object> info) {
		// TODO Auto-generated method stub
		Criteria criteria = Criteria.where("itemInfo.infoId").is(infoId);
		if (null != criteria) {
			Query query = new Query(criteria);
			mongoTemplate.remove(query, prjId.toString());

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("prjId", prjId);
			map.put("taskId", info.get("taskId"));
			map.put("itemId", info.get("itemId"));
			map.put("itemInfo", info);
			mongoTemplate.save(map, prjId.toString());
		}
	}

	@Override
	public void delItemInfo(Integer prjId, String infoId) {
		Criteria criteria = Criteria.where("itemInfo.infoId").is(infoId);
		if (null != criteria) {
			Query query = new Query(criteria);
			if (null != query) {
				mongoTemplate.remove(query, prjId.toString());
			}
		}

	}

	@Override
	public TodoListTree todoListForTask(Integer prjid, Integer targetTaskId) {
		TodoListTree todoListTree = new TodoListTree();
		boolean isTask = false;
		// 查询项目基本信息
		RtaProjectInfo rtaProjectInfo = rtaProjectInfoDAO.findById(prjid);
		if (rtaProjectInfo != null) {
			todoListTree.setId(rtaProjectInfo.getId().toString());
			todoListTree.setName(rtaProjectInfo.getProjectName());
			// 模板ID
			Integer tid = rtaProjectInfo.getRelTemplateId();

			String[] appPhaseKeys = APPP_HASE_KEY.split(",");
			List<TodoListTree> appPhaseList = new ArrayList<TodoListTree>();
			for (String keys : appPhaseKeys) {
				String[] key = keys.split(":");
				String appPhase = key[0];
				String name = key[1];
				TodoListTree appPhaseTree = new TodoListTree();
				appPhaseTree.setId(appPhase);
				appPhaseTree.setName(name);
				//
				// 查询模板对应的工作
				List<RtaWorkInfo> listRtaWorkInfo = rtaWorkInfoDAO.findByTemplateIdAppPhase(tid, appPhase);
				List<TodoListTree> workList = new ArrayList<TodoListTree>();
				for (RtaWorkInfo rtaWorkInfo : listRtaWorkInfo) {
					Integer id = rtaWorkInfo.getId();
					String workName = rtaWorkInfo.getWorkName();
					TodoListTree mapRtaWorkInfo = new TodoListTree();
					mapRtaWorkInfo.setId(id.toString());
					mapRtaWorkInfo.setName(workName);
					mapRtaWorkInfo.setAppPhase(rtaWorkInfo.getAppPhase());
					mapRtaWorkInfo.setIsWork("1");
					workList.add(mapRtaWorkInfo);

					// 查询工作对应的任务
					List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(rtaWorkInfo.getId());
					List<TodoListTree> subList = new ArrayList<TodoListTree>();
					for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
						Integer taskId = rtaTaskInfo.getRelSz();
						if (taskId != null && taskId.equals(targetTaskId)) {
							isTask = true;
							RtaTaskSzInfo rtaTaskSzInfo = rtaTaskSzInfoDAO.findById(taskId);
							if (rtaTaskSzInfo != null) {
								TodoListTree mapRtaTaskSzInfo = new TodoListTree();
								mapRtaTaskSzInfo.setId(rtaTaskSzInfo.getId().toString());
								mapRtaTaskSzInfo.setName(rtaTaskSzInfo.getTaskName());
								subList.add(mapRtaTaskSzInfo);
							}
						}
					}
					if (isTask) {
						mapRtaWorkInfo.setSubList(subList);
					}
				}
				if (isTask) {
					appPhaseTree.setSubList(workList);
					appPhaseList.add(appPhaseTree);
				}
			}
			if (isTask) {
				todoListTree.setSubList(appPhaseList);
			}
		}
		return todoListTree;
	}

	public void finishTask(Integer prjId, Integer workId, Integer taskId) {

		//
		RtaProjectInfo projectInfo = rtaProjectInfoDAO.findById(prjId);
		// 查询初始工作
		Integer templateId = projectInfo.getRelTemplateId();
		List<RtaWorkInfo> listRtaWorkInfoFirst = rtaWorkInfoDAO.findFirstByTemplateIdAll(templateId);
		Date startTime = projectInfo.getStartTime();
		projectPlan(projectInfo, templateId, taskId, listRtaWorkInfoFirst, startTime);

		checkIsCurrentTask(prjId, null);

	}

//	private void checkRunTask(Integer prjId) {
//
//		RtaProjectInfo rtaProjectInfo = rtaProjectInfoDAO.findById(prjId);
//		Integer templateId = rtaProjectInfo.getRelTemplateId();
//		
//		// 查询初始工作
//		List<RtaWorkInfo> listRtaWorkInfoFirst = rtaWorkInfoDAO.findFirstByTemplateIdAll(templateId);
//		for (RtaWorkInfo rtaWorkInfo : listRtaWorkInfoFirst) {
//			Integer isCurrent = 1;
//			// 查询工作对应的任务,计算任务时间计划
//			Integer workId = rtaWorkInfo.getId();
//			List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(workId);
//			for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
//				Integer taskId = rtaTaskInfo.getId();
//				RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjId, workId, taskId);
//				if (rtaProTaskInfo != null && rtaProTaskInfo.getIsCurrent() != null
//						&& "0".equalsIgnoreCase(rtaProTaskInfo.getIsDone()) && isCurrent == 1) {
//					rtaProTaskInfo.setIsCurrent(isCurrent);
//					isCurrent = 0;
//					rtaProTaskInfoDAO.update(rtaProTaskInfo);
//					
//				}
//
//			}
//
//		}
//
//		for (RtaWorkInfo rtaWorkInfo : listRtaWorkInfoFirst) {
//			Integer workId = rtaWorkInfo.getId();
//			checkIsCurrentTask(prjId, workId, 1);
//
//		}
//
//	}

	private void checkIsCurrentTask(Integer prjId, Integer parentWorkId) {
		RtaProjectInfo rtaProjectInfo = rtaProjectInfoDAO.findById(prjId);

		Integer templateId = rtaProjectInfo.getRelTemplateId();

		List<RtaWorkInfo> listRtaWorkInfo = null;
		// 查询单前工作的下一个工作
		if (parentWorkId == null) {
			listRtaWorkInfo = rtaWorkInfoDAO.findFirstByTemplateIdAll(templateId);
		} else {
			listRtaWorkInfo = rtaWorkInfoDAO.findByParentWorkIdForAll(templateId, parentWorkId);
		}
		//
		for (RtaWorkInfo rtaWorkInfo : listRtaWorkInfo) {
			boolean haveFirstIsCurrent = false;
			// 查询工作对应的任务,计算任务时间计划
			Integer workId = rtaWorkInfo.getId();
			if (workId == 10265) {
				haveFirstIsCurrent = false;
			}

			// 查询前置工作
			List<RtaWorkInfo> parentWorkInfos = rtaWorkInfoDAO.findParentWorkIdForAll(templateId, workId);
			// 判断前置工作是否有正在进行的任务

			for (RtaWorkInfo parentWorkInfo : parentWorkInfos) {
				List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(parentWorkInfo.getId());

				for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
					RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjId, parentWorkInfo.getId(),
							rtaTaskInfo.getId());

					if (rtaProTaskInfo != null && (rtaProTaskInfo.getIsCurrent() == RtaProTaskInfo.IS_CURRENT_YES
							|| RtaProTaskInfo.IS_DONE_NO.equalsIgnoreCase(rtaProTaskInfo.getIsDone()))) {
						haveFirstIsCurrent = true;
					}
				}
			}

//			// 查询当前工作的子工作
//			List<RtaWorkInfo> listRtaWorkInfoSun = rtaWorkInfoDAO.findByParentWorkIdForAll(templateId, workId);
//			// 查询当前工作的子工作的前置工作中是否有未完成的工作
//			for (RtaWorkInfo rtaWorkInfoSun : listRtaWorkInfoSun) {
//				// 查询前置工作
//				List<RtaWorkInfo> parentWorkInfoSun = rtaWorkInfoDAO.findParentWorkIdForAll(templateId,
//						rtaWorkInfoSun.getId());
//				for (RtaWorkInfo parentWorkInfo : parentWorkInfoSun) {
//					if (workId.intValue() != parentWorkInfo.getId().intValue()) {
//						List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(parentWorkInfo.getId());
//
//						for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
//							RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjId,
//									parentWorkInfo.getId(), rtaTaskInfo.getId());
//
//							if (rtaProTaskInfo != null
//									&& (rtaProTaskInfo.getIsCurrent() == RtaProTaskInfo.IS_CURRENT_YES
//											|| RtaProTaskInfo.IS_DONE_YES
//													.equalsIgnoreCase(rtaProTaskInfo.getIsDone()))) {
//								haveFirstIsCurrent = true;
//							}
//						}
//					}
//				}
//
//			}

			if (!haveFirstIsCurrent) {
				int isCurrent = RtaProTaskInfo.IS_CURRENT_YES;
				List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(workId);
				for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
					Integer taskId = rtaTaskInfo.getId();
					RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjId, workId, taskId);
					// 判断单前任务是否是已经完成对当前任务

					if (rtaProTaskInfo != null) {

						if (RtaProTaskInfo.IS_DONE_YES.equalsIgnoreCase(rtaProTaskInfo.getIsDone())
								&& rtaProTaskInfo.getIsCurrent() == RtaProTaskInfo.IS_CURRENT_NO) {
							// 如果任务已经完成，并且不是当前任务，不做任何处理

						} else if (RtaProTaskInfo.IS_DONE_YES.equalsIgnoreCase(rtaProTaskInfo.getIsDone())
								&& rtaProTaskInfo.getIsCurrent() == RtaProTaskInfo.IS_CURRENT_YES) {
							// 如果任务已经完成，并且是当前任务，修改成非当前任务
							//
							rtaProTaskInfo.setIsCurrent(RtaProTaskInfo.IS_CURRENT_NO);
							rtaProTaskInfoDAO.update(rtaProTaskInfo);
						} else if (RtaProTaskInfo.IS_DONE_NO.equalsIgnoreCase(rtaProTaskInfo.getIsDone())
								&& rtaProTaskInfo.getIsCurrent() == RtaProTaskInfo.IS_CURRENT_NO
								&& isCurrent == RtaProTaskInfo.IS_CURRENT_YES) {
							// 如果任务没有完成，并且不是当前任务，修改当前任务
							// 当前任务
							rtaProTaskInfo.setIsCurrent(RtaProTaskInfo.IS_CURRENT_YES);
							// 当前项目阶段
							rtaProjectInfo.setAppPhase(rtaWorkInfo.getAppPhase());
							isCurrent = RtaProTaskInfo.IS_CURRENT_NO;
							rtaProTaskInfoDAO.update(rtaProTaskInfo);
							rtaProjectInfoDAO.update(rtaProjectInfo);
						}

					}
				}

			}

		}

		for (RtaWorkInfo rtaWorkInfo : listRtaWorkInfo) {
			// 查询工作对应的任务,计算任务时间计划
			checkIsCurrentTask(prjId, rtaWorkInfo.getId());
		}
	}

	@Override
	public void commitTask(Integer prjId, Integer workId, Integer taskId, Map<String, String> userInfo) {
		// TODO
		//finishTask(prjId, workId, taskId);

		RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjId, workId, taskId);
		if (rtaProTaskInfo != null) {
			//
			Integer submitBat = rtaTaskSpLogDAO.searchMaxSubmitBat(rtaProTaskInfo.getRelProId(),
					rtaProTaskInfo.getRelWorkId(), rtaProTaskInfo.getRelTaskId());
			if (submitBat == null || submitBat < 1) {
				submitBat = 1;
			} else {
				submitBat = submitBat + 1;
			}

			List<RtaTaskSpPerson> rtaTaskSpPersons = rtaTaskSpPersonDAO.searchByTaskId(taskId);
			if (rtaTaskSpPersons != null && rtaTaskSpPersons.size() > 0) {
				for (RtaTaskSpPerson rtaTaskSpPerson : rtaTaskSpPersons) {
					// 创建审批日志
					RtaTaskSpLog rtaTaskSpLog = new RtaTaskSpLog();
					// 主键
					// rta_project_info.id
					rtaTaskSpLog.setRelProjectId(rtaProTaskInfo.getRelProId());
					// rta_work_info.id
					rtaTaskSpLog.setRelWorkId(rtaProTaskInfo.getRelWorkId());
					// rta_task_info.id
					rtaTaskSpLog.setRelTaskId(rtaProTaskInfo.getRelTaskId());
					// 完成人id
					rtaTaskSpLog.setDonePerson(userInfo.get("USER_ID"));
					// 完成人名
					rtaTaskSpLog.setDonePersonName(getUserName(userInfo.get("USER_ID")));
					// 完成人部门id
					rtaTaskSpLog.setDonePersonDept(userInfo.get("ORG_ID"));
					// 完成人部门
					rtaTaskSpLog.setDonePersonDeptName(getDeptName(userInfo.get("ORG_ID")));
					// 完成时间
					Timestamp d = new Timestamp(System.currentTimeMillis());
					rtaTaskSpLog.setDoneTime(new Date(d.getTime()));
					// **1当前审批日志 0过去审批日志
					rtaTaskSpLog.setIsCurrent("1");
					// lv
					rtaTaskSpLog.setSpLevel(rtaTaskSpPerson.getSpLevel());
					// 审批状态 0待审批 1审批通过 2驳回
					rtaTaskSpLog.setSpState("0");
					// 用户id
					rtaTaskSpLog.setSpPerson(rtaTaskSpPerson.getPersonId());
					// 用户名
					rtaTaskSpLog.setSpPersonName(rtaTaskSpPerson.getPersonName());
					// 审批部门
					rtaTaskSpLog.setSpDept(rtaTaskSpPerson.getPersonDept());
					// 审批部门名
					rtaTaskSpLog.setSpDeptName(rtaTaskSpPerson.getPersonDeptName());
					// 审批时间
					// 审批通过内容
					// 审批不通过内容
					// rta_pro_task_info.id
					rtaTaskSpLog.setRelProjectTaskId(rtaProTaskInfo.getId());

					//
					rtaTaskSpLog.setSubmitBat(submitBat);
					rtaTaskSpLogDAO.create(rtaTaskSpLog);
				}

				// 审批通过标识 1上次通过 2上次未通过
				rtaProTaskInfo.setSpFlag(RtaProTaskInfo.SP_FLAG_COMMIT);
				// 修改要件为审批提交状态
				mongoTemplateHelp.updateItemSpFlag(prjId, taskId, RtaProTaskInfo.SP_FLAG_COMMIT);
				rtaProTaskInfoDAO.update(rtaProTaskInfo);
			} else {

				rtaProTaskInfo.setSpFlag(RtaProTaskInfo.SP_FLAG_COMMIT_YES);
				rtaProTaskInfoDAO.update(rtaProTaskInfo);
				// 修改要件为审批提交状态--任务完成
				mongoTemplateHelp.updateItemSpFlag(prjId, taskId, RtaProTaskInfo.SP_FLAG_COMMIT_YES);
				// TODO
				 finishTask(prjId, workId, taskId);
			}

		}
	}

	private void projectPlan(RtaProjectInfo projectInfo, Integer templateId, Integer targetTaskId,
			List<RtaWorkInfo> listRtaWorkInfoFirst, Date startTime) {

		Integer maxDurTime = 0;
		Date nexStartTime = startTime;
		for (RtaWorkInfo rtaWorkInfoFirist : listRtaWorkInfoFirst) {
			Integer workid = rtaWorkInfoFirist.getId();
			Map map = workPlan(projectInfo, workid, targetTaskId, startTime);
			Integer newDurTime = (Integer) map.get("durTime");
			if (maxDurTime < newDurTime) {
				maxDurTime = newDurTime;
				nexStartTime = (Date) map.get("startTime");
			}
		}
		// 查询后置工作
		for (RtaWorkInfo rtaWorkInfoFirist : listRtaWorkInfoFirst) {
			Integer parentWorkId = rtaWorkInfoFirist.getId();
			List<RtaWorkInfo> listRtaWorkInfo = rtaWorkInfoDAO.findByParentWorkId(templateId, parentWorkId);

			if (listRtaWorkInfo != null && listRtaWorkInfo.size() > 0) {
				projectPlan(projectInfo, templateId, targetTaskId, listRtaWorkInfo, nexStartTime);
			}
		}
	}

	private Map workPlan(RtaProjectInfo projectInfo, Integer workid, Integer finishTargetTaskId, Date startTime) {
		// 是否有已经完成对任务
		boolean isDone = false;
		Integer totalDurTime = 0;
		// 查询工作
		RtaWorkInfo rtaWorkInfo = rtaWorkInfoDAO.findById(workid);
		// 查询前置工作
		List<RtaWorkInfo> parentWorkInfos = rtaWorkInfoDAO.findParentWorkIdForAll(projectInfo.getRelTemplateId(),
				workid);
		// 判断前置工作是否有没有完成的无限期任务
		boolean haveNullDurTime = false;
		for (RtaWorkInfo parentWorkInfo : parentWorkInfos) {
			List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkId(parentWorkInfo.getId());
			for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
				RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(projectInfo.getId(),
						parentWorkInfo.getId(), rtaTaskInfo.getId());
				if (rtaProTaskInfo != null) {
					Integer durTime = rtaTaskInfo.getDurTime();
					if ((durTime == null || durTime < 1) &&  RtaProTaskInfo.IS_DONE_NO.equalsIgnoreCase( rtaProTaskInfo.getIsDone()) ) {
						haveNullDurTime = true;
					}
				}
			}
		}

		// 查询工作对应的任务,计算任务时间计划
		List<RtaTaskInfo> listRtaTaskInfo = rtaTaskInfoDAO.findByWorkIdForAll(rtaWorkInfo.getId());
		for (RtaTaskInfo rtaTaskInfo : listRtaTaskInfo) {
			RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(projectInfo.getId(), workid,
					rtaTaskInfo.getId());
			if (rtaProTaskInfo != null) {
				Integer durTime = rtaProTaskInfo.getDurTime();
				if (durTime == null || durTime < 1) {
					haveNullDurTime = true;
				}
				if (finishTargetTaskId != null && rtaTaskInfo.getId() != null
						&& finishTargetTaskId.intValue() == rtaTaskInfo.getId().intValue()) {
					isDone = true;
					startTime = getDBDate();
					// 修改任务完成时间
					rtaProTaskInfo.setIsDone(RtaProTaskInfo.IS_DONE_YES);
					rtaProTaskInfo.setDoneTime(getDBDate());
					rtaProTaskInfoDAO.update(rtaProTaskInfo);
				}
				if (isDone) {

					if (finishTargetTaskId != null && rtaTaskInfo.getId() != null
							&& finishTargetTaskId.intValue() != rtaTaskInfo.getId().intValue()) {
						rtaProTaskInfo.setStartTime(startTime);
						rtaProTaskInfoDAO.update(rtaProTaskInfo);
						if (haveNullDurTime == false) {
							// 下一任务开始时间
							if (durTime != null && durTime > 0 && startTime != null) {
								startTime = nextWorkDate(startTime, durTime);
								totalDurTime = totalDurTime + durTime;
							} else {
								totalDurTime = 0;
								startTime = null;
							}

						}
					}
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("startTime", startTime);
		map.put("durTime", totalDurTime);
		return map;
	}

	@Override
	public void repleaseItemInfo(Integer prjId, String infoId, String msg) {

		Criteria criteria = Criteria.where("itemInfo.infoId").is(infoId);
		if (null != criteria) {
			Query query = new Query(criteria);
			List<Map> list = mongoTemplate.find(query, Map.class, prjId.toString());
			for (Map map : list) {
				Map itemInfo = (Map) map.get("itemInfo");
				itemInfo.put("替换说明", msg);
				itemInfo.put("是否替换", "是");
				mongoTemplate.remove(query, prjId.toString());

				Map<String, Object> itemInfoMap = new HashMap<String, Object>();
				Integer taskId = (Integer) itemInfo.get("taskId");
				Integer workId = (Integer) itemInfo.get("workId");
				Integer itemId = (Integer) itemInfo.get("itemId");
				
				itemInfoMap.put("prjId", prjId);
				itemInfoMap.put("taskId", taskId);
				itemInfoMap.put("workId",workId);
				itemInfoMap.put("itemId",itemId);
				itemInfoMap.put("itemInfo", itemInfo);
				//				
				mongoTemplate.save(itemInfoMap, prjId.toString());
				//
				Map<String, Object> parm = new HashMap<String, Object>();
				// rel_task_info varchar(300) COMMENT 'rta_task_info.id',
				RtaProTaskInfo rtaProTaskInfo = rtaProTaskInfoDAO.searchByTaskId(prjId, workId, taskId);
				parm.put("rel_task_info", rtaProTaskInfo.getId());
				// Modify by Wangkui 20201228
				// rel_task_item_rel varchar(300) COMMENT 'rta_task_item_rel.id',
				// Old
				// parm.put("rel_task_item_rel", itemInfo.get("itemId"));
				//New
				
				Map rtaTaskItemRel = rtaTaskItemRelDAO.findByTaskIdItemId(taskId,itemId);
				parm.put("rel_task_item_rel", rtaTaskItemRel.get("id"));
				// Modify by Wangkui 20201228 End
				//
				parm.put("rel_item_info_id", infoId);
				// is_replace varchar(50) COMMENT '1是替换 0不是',
				parm.put("is_replace", "1");
				rtaItemUploadReplaceDAO.updateReplaceInfo(parm);
			}

		}

	}

	@Override
	public List<RtaItemSzInfo> searchItemListByTaskId(Integer taskId) {

		RtaTaskInfo rtaTaskInfo = rtaTaskInfoDAO.findById(taskId);
		List<RtaTaskItemRel> rtaTaskItemRels = rtaTaskItemRelDAO.findBytaskId(rtaTaskInfo.getRelSz());
		List<RtaItemSzInfo> rtaItemInfoList = new ArrayList<RtaItemSzInfo>();
		for (RtaTaskItemRel rtaTaskItemRel : rtaTaskItemRels) {
			RtaItemSzInfo rtaItemInfo = rtaItemSzInfoDAO.findById(rtaTaskItemRel.getItemId());
			if (rtaItemInfo != null) {
				rtaItemInfo.setUploadLimit(rtaTaskItemRel.getUploadType());
				rtaItemInfoList.add(rtaItemInfo);
			}
		}

		return rtaItemInfoList;
	}
}
